package com.stone.framework.batch.tasklet;

import java.io.FileNotFoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

/**
 * 检查文件是否存在 tasklet
 * 
 * @author ybliu
 * @date 2020/07/27
 */
public class FileCheckingTasklet implements Tasklet, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileCheckingTasklet.class);

    private Resource resource;
    private long waitTime = 60 * 1000L;
    private int times = 30;

    private int count = 0;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        while (++this.count <= this.times) {
            if (resource.exists()) {
                LOGGER.info("第{}次检查...文件存在 {}", this.count, this.resource.getDescription());
                contribution.setExitStatus(ExitStatus.COMPLETED);
                return RepeatStatus.FINISHED;
            }
            LOGGER.info("第{}次检查...文件不存在 {}", this.count, this.resource.getDescription());
            Thread.sleep(this.waitTime);
        }
        throw new FileNotFoundException("文件检查超时 " + this.resource.getDescription());

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.resource, "resource must not be null");
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public void setWaitTime(long waitTime) {
        this.waitTime = waitTime;
    }

    public void setTimes(int times) {
        this.times = times;
    }

}
